;;; bir-org-noter.el --- BIR 🫶 Org-noter            -*- lexical-binding: t; -*-

;; Copyright (C) 2021  i-am

;; Author: i-am <i@fbsd>
;; Keywords: convenience

;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
;; along with this program.  If not, see <https://www.gnu.org/licenses/>.

;;; Commentary:

;; BIR intergation with Org-noter and PDF-tools.
;; TODO: Documentation.

;;; Code:

(defun org-noter-make-extract ()
  "TODO"
  (interactive)
  (org-noter--with-valid-session
   (cond ((eq major-mode 'pdf-view-mode)
          (pdf-annot-add-highlight-markup-annotation (pdf-view-active-region) "SkyBlue" '((label . "extract"))))
         (t (error "Not in document buffer.")))))

(defun org-noter-import-extract (a)
  (if (string= (pdf-annot-get a 'label) "extract")
      (org-noter--with-valid-session
       (let ((contents (pdf-info-gettext (pdf-view-current-page) (org-noter--pdf-tools-edges-to-region (pdf-annot-get-display-edges a))))
             id)
         (with-current-buffer (org-noter--session-notes-buffer session)
           (widen)
           (org-noter-insert-note (org-noter--get-precise-info) contents)
           (org-back-to-heading)
           (org-set-tags "extract")
           (org-set-property "CATEGORY" "Extract")
           (setq id  (org-id-get (point) t)))
         (with-current-buffer (org-noter--session-doc-buffer session)
           (pdf-annot-put a 'label "org-id")
           (pdf-annot-put a 'contents id))))))

(defun org-noter-goto-annot-note (a)
  (if (string= (pdf-annot-get a 'label) "org-id")
      (if (org-id-find (pdf-annot-get a 'contents))
          (progn (org-id-goto (pdf-annot-get a 'contents))
                  t)
        (message "No org entry with an ID matching \"%s\"" (pdf-annot-get a 'contents))
        nil)))

(add-hook 'pdf-annot-activate-handler-functions 'org-noter-import-extract)

(add-hook 'pdf-annot-activate-handler-functions 'org-noter-goto-annot-note)

(provide 'bir-org-noter)
;;; bir-org-noter.el ends here
